package com.lingz.manager.common.utils;

import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;

public class GetMACAddr {
    /**
     * 我们通过NetworkInterface这个类来操作。
     * 也就是通过getLocalHost()方法先得到本机IP，
     * 然后调用getHardwareAddress()方法得到一个byte数组的地址。
     * 我们把六位地址传到一个byte数组里面，然后输出来就是。
     * **/
    public static String getMACAddr() {
        String str = "";
        // 获得ＩＰ
     NetworkInterface netInterface = null;
        try {
            netInterface = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        // 获得Mac地址的byte数组
            byte[] macAddr = new byte[0];
        try {
            macAddr = netInterface.getHardwareAddress();
        }catch (SocketException e) {
            e.printStackTrace();
        }
           // System.out.print("MAC Addr:\t");
            // 循环输出
            for (byte b : macAddr) {
            // 这里的toHexString()是自己写的格式化输出的方法，见下步。
            //System.out.print(toHexString(b) + " ");
            str = str+toHexString(b);
        }
            return str;
    }
    // 获取CPU序列号
    @SuppressWarnings("resource")
    public static String getCpuInfo(){
        try {
            Process process = Runtime.getRuntime().exec(
                    new String[] { "wmic", "cpu", "get", "ProcessorId" });
            process.getOutputStream().close();
            Scanner sc = new Scanner(process.getInputStream());
            String property = sc.next();
            String serial = sc.next();
           // System.out.println(property + ": " + serial);
            return serial;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String toHexString(int integer) {
            // 将得来的int类型数字转化为十六进制数
            String str = Integer.toHexString((int) (integer & 0xff));
            // 如果遇到单字符，前置0占位补满两格
            if (str.length() == 1) {
            str = "0" + str;
            }
            return str;
   }
    public static void main(String[] args) throws SocketException, UnknownHostException {
                 System.out.print(getMACAddr());
                 System.out.print(getCpuInfo());
    }
}
